<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>新增期初</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
          name: 'temporary',
          value: 0
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '98%'
        });
        
        //供应商
        var vendor = Ext.create('Ext.form.ComboBox', {
          store: vendorStore,
          fieldLabel: '供应商',
          allowBlank: false,
          blankText: "供应商必须选择",
          valueField: 'id',
          displayField: 'name',
          name: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',          
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,          
          readOnly:false,
          minChars: 0,
          editable:false
        });

        vendor.on('select', function(combo, record, index) {          
          if (record[0].get('linkman') === "" ){
            linkman.setValue(record[0].get('name'));
          }else{
            linkman.setValue(record[0].get('linkman'));
          }
          phone.setValue(record[0].get('phone'));

        });
        

        //要求期初时间
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '期初日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "期初日期必须选择",
          emptyText: '期初日期...',
          anchor: '95%'
        });

        //所有仓库
        var toWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'warehouse_id',
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,
          minChars: 0,
          editable:false
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false,
          anchor: '95%'
        });
        
        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系电话',
          name: 'phone',
          allowBlank: false,
          anchor: '95%'
        });

        //税率
        var taxRate = Ext.create('Ext.form.field.Number', {
          fieldLabel: '税率(%)',
          name:"tax_rate",
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          maxValue: 100,
          value:17,
          anchor: '95%'
        });


        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '总金额',
          name:"amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          anchor: '90%'
        });

        //总进项税
        var sumVATAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '总税额',
          name:"value_added_tax_amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          anchor: '90%'
        });

        //含税总金额
        var sumTaxAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '含税总金额',
          name:"tax_amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          anchor: '90%'
        });
        
        //--------------------------------------------------------------------------
        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productAllInfoStore,
          emptyText: '请选择...',
          displayField: 'name',
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
            }
          }
        });

        productCBB.on('select', function(combo, record, index) {
          var sm = openingStockGrid.getSelectionModel();
          var records = sm.getSelection();
          var openingStockItemRecord = records[0];
          
          if (!openingStockItemRecord) {
            return false;
          }
          if (isDuplicateByProduct(openingStockDS,record[0].get('id'),openingStockItemRecord.id)){
            //删除当前记录
            openingStockDS.remove(openingStockItemRecord);
          }else{
            if (openingStockItemRecord.get('product_id') != record[0].get('id')){
              openingStockItemRecord.set('number',record[0].get('number'));
              openingStockItemRecord.set('spec',record[0].get('spec'));
              openingStockItemRecord.set('unit',record[0].get('unit'));
              openingStockItemRecord.set('unit_price',record[0].get('unit_price'));
              openingStockItemRecord.set('amount',record[0].get('unit_price'));
              openingStockItemRecord.set('quantity',1);
              openingStockItemRecord.set('product_id',record[0].get('id'));
              //判断套装
              openingStockItemRecord.set('is_suit',record[0].get('is_suit'));
            }
          }
        });

        //期初列表Grid Store
        var openingStockDS = Ext.create('Ext.data.Store', {
          //autoDestroy : true,
          model : 'OpeningStockDetailModel',
          proxy : {
            type : 'ajax',
            //url : '/opening_stock/getOpeningStockDetailsById',
            reader : {
              type : 'json',
              root : 'root',// JSON数组对象名
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });

        //生成要订单的产品的Grid
        var openingStockGrid = Ext.create('Ext.grid.Panel', {
          store: openingStockDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: '产品名称',
              dataIndex: 'product_name',
              field: productCBB,
              width: 370
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: true
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 85
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              align: 'right',
              width: 50
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.000000000'),
              width: 110
            },{
              header: '金额',
              dataIndex: 'amount',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 70
            },{
              header: '含税单价',
              dataIndex: 'tax_price',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: true,
                minValue: 0,
                decimalPrecision: 2
              }),
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '进项税',
              dataIndex: 'value_added_tax',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 70
            },{
              header: '含税金额',
              dataIndex: 'tax_amount',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '套装?',
              dataIndex: 'is_suit',
              width: 50
            },{
              header: '备注',
              dataIndex: 'description',
              width: 130,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '100%'
              })
            }],
          selModel : Ext.create('Ext.selection.CheckboxModel'),
          width: 1125,
          height: 340,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){

                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, openingStockGrid.getStore().model);
                openingStockDS.insert(0, record);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = openingStockGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                openingStockDS.remove(records);
              }
            }]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '保存期初表单。',
          iconCls: 'icon-save',
          handler: function(){
            if (openingStockFormPanel.form.isValid()) {
              
              var productsJsonStr = gridStoreToJson(openingStockDS,rejectKeyArray);
              if (openingStockDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //这儿要判断一下，是不是所有的含税单价已经完全输入了。
              if (checkTaxPrice() == false){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有没有输入含税单价的产品，请检查后提交！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = openingStockFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/opening_stock/create',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存期初订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  newOpeningStockWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
          text: '暂存',
          tooltip: '暂时保存期初订单。',
          iconCls: 'temp-save',
          handler: function(){
            //首先把临时变量设置为1
            temporary.setValue(1);

            if (openingStockFormPanel.form.isValid()){
              
              var productsJsonStr = gridStoreToJson(openingStockDS,rejectKeyArray);
              if (openingStockDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (openingStockDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //这儿要判断一下，是不是所有的含税单价已经完全输入了。
              if (checkTaxPrice() == false){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有没有输入含税单价的产品，请检查后提交！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = openingStockFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/opening_stock/create',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "暂存期初订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  newOpeningStockWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newOpeningStockWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var openingStockFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 65,
            labelAlign: 'right'
          },
          width: '1140',
          frame : true,
          url: '/opening_stock/create',
          method: 'GET',
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [vendor]
                }, {
                  columnWidth: .25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }, {
                  columnWidth: .35,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toWarehouse]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [linkman]
                }, {
                  columnWidth: .25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [phone]
                }, {
                  columnWidth: .35,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [taxRate]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [openingStockGrid]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 0.25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sumAmount]
                },{
                  columnWidth: 0.25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sumVATAmount]
                },{
                  columnWidth: 0.25,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sumTaxAmount]
                }]
            },temporary],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        openingStockFormPanel.render('new_opening_stock');
        //
        openingStockGrid.on('edit', afterEdit, this );

        function afterEdit(editor,obj,options) {
          // execute an XHR to send/commit data to the server, in callback do (if successful):
          if(obj.field=="product_name"||obj.field=="quantity"||obj.field=="tax_price"){
            if(obj.record.get('quantity')>0 && obj.record.get('tax_price') >0){
              //设置含税单价和含税竞价
              obj.record.set('unit_price',Math.round(10000000000*obj.record.get('tax_price')/(1+taxRate.getValue()*0.01))/10000000000);
              obj.record.set('tax_amount',obj.record.get('tax_price')*obj.record.get('quantity'));
              obj.record.set('amount',Math.round(obj.record.get('quantity')*100*obj.record.get('unit_price'))/100);
              obj.record.set('value_added_tax',Math.round(obj.record.get('amount')*taxRate.getValue()*0.01*1000)/1000);
            }else{
              obj.record.set('amount',0);
            }
          }
          getSumAmount();
        }

        function getSumAmount(){
          sumAmount.setValue(0);
          sumVATAmount.setValue(0);
          sumTaxAmount.setValue(0);
          var records = openingStockDS.getRange(0,openingStockDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var quantity = record.get('quantity');
            var unitPrice = record.get('unit_price');
            var taxPrice = record.get('tax_price');
            //record.set('amount',quantity*unitPrice);
            //record.set('tax_amount',quantity*taxPrice);
            //var amount = record.get('amount');
            sumAmount.setValue(sumAmount.getValue()+record.get('amount'));
            sumVATAmount.setValue(sumVATAmount.getValue()+record.get('value_added_tax'));
            sumTaxAmount.setValue(sumTaxAmount.getValue()+record.get('tax_amount'));
          }
        }

        //检查一下含税单价是否完全输入了。
        function checkTaxPrice(){
          //这儿要判断一下，是不是所有的含税单价已经完全输入了。
          var records = openingStockDS.getRange(0,openingStockDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var recordTaxPrice = record.get('tax_price');
            if (recordTaxPrice == undefined){
              return false;
              break;
            }
          }
        }
      })
    </script>
  </head>
  <body>
    <div id="new_opening_stock"></div>
  </body>
</html>